import { Message } from 'element-ui'
import { Toast } from 'vant'
import Vue from 'vue'
import router from '../router'

// 判断请求状态
export const iscode = res => {
  if (res.code === 0) {
    return true
  } else if (res.code === 500) {
    router.push('/noFound')
    return false
  } else {
    let screenWidth = document.body.clientWidth || document.documentElement.clientWidth
    if (screenWidth <= 768) {
      Toast(res.message)
    } else {
      Message({
        message: res.message,
        iconClass: 'myErrorIcon',
        customClass: 'myError'
      })
    }
    // if (res.code === 400001) {
    //   router.push('/')
    // }
    return false
  }
}

//中国标准时间转换成年月日
export const dayChange = time => {
  let date = new Date(time)
  let y = date.getFullYear()
  let m = date.getMonth() + 1
  m = m < 10 ? '0' + m : m
  let d = date.getDate()
  d = d < 10 ? '0' + d : d
  return y + '-' + m + '-' + d
}

//提示
export const showMessage = (message, type) => {
  if (isPhone()) {
    Toast(message)
  } else {
    Message({
      message: message,
      type: type
    })
  }
}

//获取设备宽度
export const getWidth = () => {
  let screenWidth = document.body.clientWidth || document.documentElement.clientWidth
  return screenWidth
}

//监听本地存储
export const watchlocalstorage = () => {
  const signSetItem = localStorage.setItem
  localStorage.setItem = function(key, val) {
    const setEvent = new Event('setItemEvent')
    setEvent.key = key
    setEvent.value = val
    window.dispatchEvent(setEvent)
    signSetItem.apply(this, arguments)
  }
}

//时间戳转年月日时分秒
export const getYMDHMS = timestamp => {
  let time = new Date(timestamp * 1000)
  let year = time.getFullYear()
  let month = time.getMonth() + 1
  let date = time.getDate()
  let hours = time.getHours()
  let minute = time.getMinutes()
  let second = time.getSeconds()
  if (month < 10) {
    month = '0' + month
  }
  if (date < 10) {
    date = '0' + date
  }
  if (hours < 10) {
    hours = '0' + hours
  }
  if (minute < 10) {
    minute = '0' + minute
  }
  if (second < 10) {
    second = '0' + second
  }
  return year + '-' + month + '-' + date + ' ' + hours + ':' + minute + ':' + second
}

//判断是否是微信内置浏览器
export const isWeixin = () => {
  var ua = navigator.userAgent.toLowerCase()
  if (ua.match(/MicroMessenger/i) == 'micromessenger') {
    return true
  } else {
    return false
  }
}

// 判断是否是ios
export const isIOS = () => {
  // const u = navigator.userAgent;
  // const isios = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
  // if (isios) {
  //   return true;
  // } else {
  //   return false;
  // }

  if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
    //判断iPhone|iPad|iPod|iOS
    return true
  } else if (/(Android)/i.test(navigator.userAgent)) {
    //判断Android
    return false
  } else {
    //pc
    if (/Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent)) {
      return true
    } else {
      return false
    }
  }
}

//判断是否是手机
export const isPhone = () => {
  let screenWidth = document.body.clientWidth || document.documentElement.clientWidth
  if (screenWidth <= 768) {
    return true
  } else {
    return false
  }
}

// 解决安卓软键盘收回后页面留白的问题（参数：1.当前组件最外侧元素的id名，2.vue实例this）
export const reHeight = (dom, that) => {
  var originHeight = document.documentElement.clientHeight || document.body.clientHeight
  that.$nextTick(() => {
    let bodyE = document.querySelector('#' + dom)
    window.addEventListener(
      'resize',
      function() {
        var resizeHeight = document.documentElement.clientHeight || document.body.clientHeight
        if (originHeight < resizeHeight) {
          // console.log("Android 键盘收起啦！");
          // Android 键盘收起后操作
          bodyE.style.height = 100 + '%'
        } else {
          // console.log("Android 键盘弹起啦！");
          // Android 键盘弹起后操作
          bodyE.style.height = originHeight + 'px'
        }
        originHeight = resizeHeight
      },
      false
    )
  })
}

export const stopBodyMove = () => {
  let move = e => {
    e.preventDefault()
  }
  document.body.style.overflow = 'hidden'
  document.addEventListener('touchmove', move, { passive: false })
}

export const startBodyMove = () => {
  let move = e => {
    e.preventDefault()
  }
  document.body.style.overflow = ''
  document.removeEventListener('touchmove', move, { passive: true })
}

export const protectNumber = number => {
  if (number.length == 11) {
    let trimNumber = number.replace(/^(.{3}).*(.{4})$/, '$1****$2')
    return trimNumber
  } else {
    return number
  }
}

export const escapeHTML = untrusted => {
  return untrusted
    .replace(/<(?:.|\n)*?>/gm, '')
    .replace(/(&rdquo;)/g, '"')
    .replace(/&ldquo;/g, '"')
    .replace(/&mdash;/g, '-')
    .replace(/&nbsp;/g, '')
    .replace(/&gt;/g, '>')
    .replace(/&lt;/g, '<')
    .replace(/<[\w\s"':=\/]*/, '')
}

// 左右缓动动画
export const animalAction = (obj, target, callback) => {
  // <必传> obj: 作用的元素
  // <必传> target: 目的地offsetLeft值
  // <选传> callback: 回调函数

  // 先清除以前的定时器
  clearInterval(obj.timer)
  obj.timer = setInterval(() => {
    // 定义步长:（目标值 - 当前值） / 10
    let step = (target - obj.offsetLeft) / 10

    // 避免小数的问题
    step = step > 0 ? Math.ceil(step) : Math.floor(step)

    // 结束条件
    if (obj.offsetLeft === target) {
      clearInterval(obj.timer)
      // 如果传了回调函数，则定时器结束时执行
      if (callback) {
        callback()
      }
    }
    obj.style.left = obj.offsetLeft + step + 'px'
  }, 15)
}

/**
 *判断是否是app环境
 */
export function isApp() {
  var ua = navigator.userAgent.toLowerCase()
  if (ua.match(/isapp/i) == 'isapp') {
    return true
  }
  return false
}
